import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getCurrentUser, isAdmin } from '@/middleware/auth';
import { AuthService } from '@/lib/auth';
import { Permission } from '@/lib/db/auth-schema';

/**
 * 获取权限列表
 */
export async function GET(request: NextRequest) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果中间件没有设置用户信息，直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const tokenFromHeader = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
      const tokenFromCookie = request.cookies.get('auth-token')?.value;
      
      const token = tokenFromHeader || tokenFromCookie;
      
      if (!token) {
        return NextResponse.json(
          { success: false, error: '未认证' },
          { status: 401 }
        );
      }
      
      const verification = await AuthService.verifyToken(token);
      if (!verification.valid || !verification.payload) {
        return NextResponse.json(
          { success: false, error: '认证无效' },
          { status: 401 }
        );
      }
      
      currentUser = verification.payload;
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const search = searchParams.get('search') || '';
    const category = searchParams.get('category') || '';
    const resourceType = searchParams.get('resource_type') || '';
    const isActive = searchParams.get('is_active');
    const sortBy = searchParams.get('sort_by') || 'created_at';
    const sortOrder = searchParams.get('sort_order') || 'desc';

    const db = await getDb();

    // 构建查询过滤器
    const filter: any = {};
    if (search) {
      filter.$or = [
        { name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
        { display_name: { $regex: search, $options: 'i' } }
      ];
    }
    if (category) filter.category = category;
    if (resourceType) filter.resource_type = resourceType;
    if (isActive !== null) filter.is_active = isActive === 'true';

    // 获取权限列表
    const permissionsResult = await db.findMany<Permission>('permissions', filter, {
      page,
      pageSize: limit,
      sortBy,
      sortOrder: sortOrder as 'asc' | 'desc'
    });
    const permissions = permissionsResult.success ? permissionsResult.data || [] : [];

    // 获取总数
    const countResult = await db.count('permissions', filter);
    const total = countResult.success ? countResult.data || 0 : 0;

    // 获取统计信息
    const allPermissionsResult = await db.findMany<Permission>('permissions', {});
    const allPermissions = allPermissionsResult.success ? allPermissionsResult.data || [] : [];
    
    // 按类别统计
    const categoryStats = allPermissions.reduce((acc: any[], permission) => {
      const existing = acc.find(item => item.category === permission.category);
      if (existing) {
        existing.count++;
      } else {
        acc.push({ category: permission.category, count: 1 });
      }
      return acc;
    }, []);

    // 按资源类型统计
    const resourceTypeStats = allPermissions.reduce((acc: any[], permission) => {
      const existing = acc.find(item => item.resource_type === permission.resource_type);
      if (existing) {
        existing.count++;
      } else {
        acc.push({ resource_type: permission.resource_type, count: 1 });
      }
      return acc;
    }, []);

    return NextResponse.json({
      success: true,
      data: permissions,
      total,
      page,
      limit,
      stats: {
        total: allPermissions.length,
        active: allPermissions.filter(p => p.is_active).length,
        inactive: allPermissions.filter(p => !p.is_active).length,
        categoryStats,
        resourceTypeStats
      }
    });

  } catch (error) {
    console.error('获取权限列表失败:', error);
    return NextResponse.json(
      { success: false, error: '获取权限列表失败' },
      { status: 500 }
    );
  }
}

/**
 * 创建新权限
 */
export async function POST(request: NextRequest) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果中间件没有设置用户信息，直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const tokenFromHeader = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
      const tokenFromCookie = request.cookies.get('auth-token')?.value;
      
      const token = tokenFromHeader || tokenFromCookie;
      
      if (!token) {
        return NextResponse.json(
          { success: false, error: '未认证' },
          { status: 401 }
        );
      }
      
      const verification = await AuthService.verifyToken(token);
      if (!verification.valid || !verification.payload) {
        return NextResponse.json(
          { success: false, error: '认证无效' },
          { status: 401 }
        );
      }
      
      currentUser = verification.payload;
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { name, display_name, description, category, resource_type, resource_id, action, is_active = true } = body;

    // 验证必填字段
    if (!name || !display_name || !category || !resource_type || !action) {
      return NextResponse.json(
        { success: false, error: '缺少必填字段' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查权限名称是否已存在
    const existingPermissionResult = await db.findOne<Permission>('permissions', { name });
    
    if (existingPermissionResult.success && existingPermissionResult.data) {
      return NextResponse.json(
        { success: false, error: '权限名称已存在' },
        { status: 409 }
      );
    }

    // 创建权限
    const permissionId = `perm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const now = new Date().toISOString();

    const permissionData: Partial<Permission> = {
      id: permissionId,
      name,
      display_name,
      description: description || '',
      category,
      resource_type,
      resource_id: resource_id || null,
      action,
      is_active,
      created_at: now,
      updated_at: now
    };

    const createResult = await db.create<Permission>('permissions', permissionData);

    if (!createResult.success) {
      return NextResponse.json(
        { success: false, error: '创建权限失败' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      data: createResult.data,
      message: '权限创建成功'
    });

  } catch (error) {
    console.error('创建权限失败:', error);
    return NextResponse.json(
      { success: false, error: '创建权限失败' },
      { status: 500 }
    );
  }
}